//
//  UIView+TalkfunActivityIndicator.m
//  CloudLive
//
//  Created by 孙兆能 on 16/8/24.
//  Copyright © 2016年 Talkfun. All rights reserved.
//

#import "UIView+TalkfunActivityIndicator.h"

#import <objc/runtime.h>
#define SCREENWIDTH [UIScreen mainScreen].bounds.size.width

#define UIColorFromRGBHex(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#define BLUECOLOR UIColorFromRGBHex(0x56acf5)
#define GRAYCOLOR UIColorFromRGBHex(0xd5d5d5)
#define DARKBLUECOLOR UIColorFromRGBHex(0x222a46)
#define NEWBLUECOLOR UIColorFromRGBHex(0x303a5e)
#define LIGHTBLUECOLOR UIColorFromRGBHex(0x93a9d1)
#define DEVICEMODEL [UIDevice currentDevice].model
#define IsIPAD [DEVICEMODEL hasPrefix:@"iPad"]
#define DismissToastDuration 0.2
@implementation UIView (TalkfunActivityIndicator)

static NSString * alertKey = @"alertKey";

- (void)setAlertController:(UIAlertController *)alertController
{
    objc_setAssociatedObject(self, &alertKey, alertController, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (UIAlertController *)alertController
{
    return objc_getAssociatedObject(self, &alertKey);
}

- (void)alert:(NSString *)title message:(NSString *)message
{
    self.alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [self.alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil]];
    
    UIViewController * vc = [self topViewController];
    if (vc) {
        if (IsIPAD) {
            self.alertController.popoverPresentationController.sourceView = vc.view;
            self.alertController.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
        }
        [vc presentViewController:self.alertController animated:YES completion:nil];
    }
}

- (UIViewController *)topViewController {
    UIWindow *keyWindow = nil;
    if (@available(iOS 13.0, *)) {
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive) {
                keyWindow = windowScene.windows.firstObject;
                break;
            }
        }
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        keyWindow = [UIApplication sharedApplication].keyWindow;
#pragma clang diagnostic pop
    }
    UIViewController *rootViewController = keyWindow.rootViewController;
    return [self topViewControllerWithRootViewController:rootViewController];
}

- (UIViewController *)topViewControllerWithRootViewController:(UIViewController *)rootViewController {
    if (rootViewController.presentedViewController == nil) {
        return rootViewController;
    }

    if ([rootViewController.presentedViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navigationController = (UINavigationController *)rootViewController.presentedViewController;
        UIViewController *lastViewController = [[navigationController viewControllers] lastObject];
        return [self topViewControllerWithRootViewController:lastViewController];
    }

    UIViewController *presentedViewController = (UIViewController *)rootViewController.presentedViewController;
    return [self topViewControllerWithRootViewController:presentedViewController];
}
- (void)alertStyle:(UIAlertControllerStyle)preferredStyle title:(NSString *)title message:(NSString *)message action:(UIAlertAction *)action
{
    self.alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:preferredStyle];
    [self.alertController addAction:action];
    [self.alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.alertController = nil;
    }]];
    
    UIViewController * vc = [self topViewController];
    if (vc) {
        if (IsIPAD) {
            self.alertController.popoverPresentationController.sourceView = vc.view;
            self.alertController.popoverPresentationController.sourceRect = CGRectMake(0,0,1.0,1.0);
        }
        [vc presentViewController:self.alertController animated:YES completion:nil];
    }
}

//开始动画
- (void)startAnimation
{
    if (@available(iOS 13.0, *)) {
        [self indicatorStyle:UIActivityIndicatorViewStyleMedium];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [self indicatorStyle:UIActivityIndicatorViewStyleWhite];
#pragma clang diagnostic pop
    }
}
- (void)startBigAnimation
{
    if (@available(iOS 13.0, *)) {
        [self indicatorStyle:UIActivityIndicatorViewStyleLarge];
    } else {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
        [self indicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
#pragma clang diagnostic pop
    }
}

- (void)indicatorStyle:(UIActivityIndicatorViewStyle)style
{
    @synchronized (self) {
        [self stopAnimation];
        UIActivityIndicatorView * indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:style];
        indicator.center = CGPointMake(self.center.x, self.center.y - 50);
        indicator.tag = 991;
        indicator.color = UIColorFromRGBHex(0x333333);
        
        
        indicator.layer.shadowOffset = CGSizeMake(1, 1);
        indicator.layer.shadowOpacity = 0.3;
        indicator.layer.shadowColor = [UIColor lightGrayColor].CGColor;
        dispatch_async(dispatch_get_main_queue(), ^{
            [self addSubview:indicator];
            [indicator startAnimation];
        });
    }
}

//结束动画
- (void)stopAnimation
{
    @synchronized (self) {
        UIActivityIndicatorView * indicator = (UIActivityIndicatorView *)[self viewWithTag:991];
        dispatch_async(dispatch_get_main_queue(), ^{
                              [indicator stopAnimation];
                              [indicator removeFromSuperview];
        });
        indicator.tag = 991;
        indicator = nil;
    }
}

//是否在动画
- (BOOL)isAnimating
{
    UIActivityIndicatorView * indicator = (UIActivityIndicatorView *)[self viewWithTag:991];
    if (!indicator) {
        return NO;
    }
    else
    {
        return indicator.isAnimating;
    }
}

static NSTimer * timer;
static NSTimer * timer2;
- (void)downloadToast:(NSString *)string position:(CGPoint)position{
    [self toast:string position:position isDownloadToast:true];
}
- (void)hideToast2
{
    [self untoast2];
    [timer2 invalidate];
    timer2 = nil;
}

- (void)untoast2
{
    dispatch_async(dispatch_get_main_queue(), ^{
        __block UIButton * button = (UIButton *)[self viewWithTag:919];
        [UIView animateWithDuration:DismissToastDuration animations:^{
            button.alpha = 0;
        } completion:^(BOOL finished) {
            [button removeFromSuperview];
        }];
    });
}
- (CGRect)getRectWithString:(NSString *)string size:(CGSize)size fontSize:(CGFloat)fontSize
{
    if ([string isKindOfClass:[NSString class]]) {
        NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
        NSStringDrawingUsesFontLeading;
        
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineBreakMode:NSLineBreakByWordWrapping];
        
        NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:fontSize], NSParagraphStyleAttributeName : style };
        
        CGRect frame = [string boundingRectWithSize:size options:opts attributes:attributes context:nil];
        CGRect rect = CGRectMake(frame.origin.x, frame.origin.y, ceil(frame.size.width), ceil(frame.size.height));
        return rect;
    }
    else
    {
        return CGRectZero;
    }
}
- (void)toast:(NSString *)string position:(CGPoint)position isDownloadToast:(BOOL)isDownloadToast
{
    UIButton * button = [(UIButton *)self viewWithTag:919];
    if (!button) {
        button = [UIButton buttonWithType:UIButtonTypeCustom];
     
        if(isDownloadToast)
        {
            button.backgroundColor = [UIColor redColor];
            [button setTitleColor:UIColorFromRGBHex(0xffffff) forState:UIControlStateNormal];
        }else
        {
            button.backgroundColor = UIColorFromRGBHex(0x444444);
            [button setTitleColor:UIColorFromRGBHex(0xffffff) forState:UIControlStateNormal];
        }
     
        button.layer.cornerRadius = 4;
        button.tag = 919;
        [button addTarget:self action:@selector(untoast2) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
    }
    button.alpha = 1;
    if (string && [string isKindOfClass:[NSString class]] && ![string containsString:@"{"]) {
        NSArray * arr = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@".?;'[]{}+_)(*&^%$#@!~`| \\。？：“？）（+——*&……%￥#@！~·"]];
        string = [arr componentsJoinedByString:@""];
    }
    
    [button setTitle:string forState:UIControlStateNormal];
    CGRect rect = [self getRectWithString:string size:CGSizeMake([UIScreen mainScreen].bounds.size.width, 40) fontSize:15];
    button.frame = CGRectMake(0, 0, rect.size.width + 20, 38);
    
    if (CGPointEqualToPoint(position, CGPointZero)) {
        button.center = self.center;
    }
    else
    {
        button.center = position;
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self addSubview:button];
    });
    
    if(timer2)
    {
        [timer2 invalidate];
        timer2 = nil;
        [self untoast2];
    }
  
    //TOASTDURATION
    timer2 = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(hideToast2) userInfo:nil repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:timer2 forMode:NSRunLoopCommonModes];
}
- (void)toast:(NSString *)string position:(CGPoint)position
{
    [self toast:string position:position isDownloadToast:false];
}

- (void)hideToast
{
    [self untoast];
    [timer invalidate];
}

- (void)InitWithImage:(UIImage *)image position:(CGPoint)position
{
    
    UIImageView *imageView = [[UIImageView alloc]init];
    imageView.image = image;
    imageView.frame =  CGRectMake(0, self.center.y - 40, 30, 30);
    imageView.tag = 999;
    
    [self addSubview:imageView];
    
}

- (UIButton *)getToastBtn
{
    UIButton * button = (UIButton *)[self viewWithTag:919];
    return button;
}

- (UIImageView*)getToastImageView
{
    
    UIImageView * ImageView = (UIImageView *)[self viewWithTag:999];
    
    return ImageView;
}

- (void)untoast
{
    [self untoast2];
}

- (BOOL)isToast
{
    UIButton * button = (UIButton *)[self viewWithTag:919];
    if (button.alpha == 0) {
        return NO;
    }
    else
    {
        return YES;
    }
}

- (UIView *)networkUnusualView:(NSString*)content
{
    if ([self containsNetworkUnusualView]) {
        return nil;
    }
    CGFloat imageW = (44 - 22) / 2;
   
    NSDictionary *attrs = @{NSFontAttributeName : [UIFont boldSystemFontOfSize:15]};
    CGSize size = [content sizeWithAttributes:attrs];
    
    
    UIView * networkView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 44)];
    networkView.tag = 777;
    networkView.backgroundColor = [UIColor colorWithRed:255/255.0 green:235/255.0 blue:235/255.0 alpha:1.0];
    

    
    UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_pop up_warning"]];
    imageView.frame = CGRectMake((CGRectGetWidth(networkView.frame) - size.width - 22)/2 , imageW, 22, 22);
    [networkView addSubview:imageView];
    
    
  
    
    
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(imageView.frame), CGRectGetMinY(imageView.frame), size.width, 22)];
//    label.backgroundColor = [UIColor redColor];
      label.text = content;
    label.font = [UIFont systemFontOfSize:15];
    label.textColor = UIColorFromRGBHex(0x666666);
    
    [networkView addSubview:label];
    
    return networkView;
}

- (void)removeNetworkUnusualView
{
    UIView * view = [self viewWithTag:777];
    if (view.superview || view) {
        [view removeFromSuperview];
        view = nil;
    }
}

- (BOOL)containsNetworkUnusualView
{
    UIView * view = [self viewWithTag:777];
    if (view) {
        return YES;
    }
    else
    {
        return NO;
    }
}
-(void)Logintoast:(NSString *)string position:(CGPoint)position
{
    UIButton * button = [(UIButton *)self viewWithTag:1008];
    if (!button) {
        button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.backgroundColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.7];
        [button setTitleColor:[UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0] forState:UIControlStateNormal];
        button.layer.cornerRadius = 6;
        button.tag = 1008;
        [button addTarget:self action:@selector(unlogintoast) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
    }
    button.alpha = 1;
    
    if (string && [string isKindOfClass:[NSString class]] && ![string containsString:@"{"]) {
        NSArray * arr = [string componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@".?;'[]{}+_)(*&^%$#@!~`| \\。？：“？）（+——*&……%￥#@！~·"]];
        string = [arr componentsJoinedByString:@""];
    }
   
    [button setTitle:string forState:UIControlStateNormal];

    CGRect rect = [self getRectWithString:string size:CGSizeMake(SCREENWIDTH, 44) fontSize:16];
    button.frame = CGRectMake(0, 0, rect.size.width + 30, 44);
    
    if (CGPointEqualToPoint(position, CGPointZero)) {
        button.center = self.center;
    }
    else
    {
        button.center = position;
    }
    

    dispatch_async(dispatch_get_main_queue(), ^{
        [self addSubview:button];
    });
    if(timer)
    {
        [timer invalidate];
        timer = nil;
        [self unlogintoast];
    }
   
    timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(hideloginToast) userInfo:nil repeats:NO];
     [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
-(void)hideloginToast
{
    [self unlogintoast];
    [timer invalidate];
    timer = nil;
}
-(void)unlogintoast
{
    __block UIButton * button = (UIButton *)[self viewWithTag:1008];
    dispatch_async(dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:DismissToastDuration animations:^{
            button.alpha = 0;
        } completion:^(BOOL finished) {
            [button removeFromSuperview];
        }];
    });
}
@end

